package shop.yaojianfeng.springlearning.section6.service.impl;


import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import shop.yaojianfeng.springlearning.section6.entity.Order;
import shop.yaojianfeng.springlearning.section6.service.OrderService;

import java.io.IOException;
import java.util.Map;

/**使用注解进行声明式事务配置
 * @author yaojianfeng
 */
@Service("txOrderService")
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    NamedParameterJdbcTemplate namedJdbcTemplate;


    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED,timeout = -1,rollbackFor = RuntimeException.class)
    public int insertOrder(Order order) {
        String sql ="insert into orders ( oid,creatTime,money,username) values (:oid,:creatTime,:money,:username)";
        Map<String, Object> map = BeanUtil.beanToMap(order);

        int update = namedJdbcTemplate.update(sql, map);
        System.out.println(10/0);

        return update;
    }
    

    @Override
    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.SUPPORTS,rollbackFor = {IOException.class,ArithmeticException.class})
    public int updateOrder(Order order) {
        String sql ="update orders set money =:money where name=:name";
        Map<String, Object> params = BeanUtil.beanToMap(order);

        return namedJdbcTemplate.update(sql,params);
    }


}
